package com.lhkj.ct.meta.modules.questionnaire.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lhkj.ct.base.utils.Validate;
import com.lhkj.ct.meta.modules.gauge.common.enums.GaugeType;
import com.lhkj.ct.meta.modules.psychology.model.dto.ProcessDto;
import com.lhkj.ct.meta.modules.psychology.model.dto.ScaleSubmitDto;
import com.lhkj.ct.meta.modules.psychology.service.GaugeAnswerService;
import com.lhkj.ct.meta.modules.questionnaire.mapper.QnrAllotRecordMapper;
import com.lhkj.ct.meta.modules.questionnaire.mapper.QnrResultMapper;
import com.lhkj.ct.meta.modules.questionnaire.model.entity.TblQnrAllotRecord;
import com.lhkj.ct.meta.modules.questionnaire.model.entity.TblQnrResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 *  问卷作答
 */
@Service
public class QnrAnswerService{

    @Resource
    private GaugeAnswerService gaugeAnswerService;

    @Resource
    private QnrResultMapper resultMapper;

    @Resource
    private QnrAllotRecordMapper qnrAllotRecordMapper;

    /**
     * 保存作答进度
     *
     * @param entity
     */
    @Transactional
    public int saveProcess(ProcessDto entity) {
        return resultMapper.updateById(new TblQnrResult(){{
            setAnswerJson(entity.getAnswerJson());
            setCostTime(entity.getCostTime());
            setId(entity.getRId());}});
//        gaugeAnswerService.saveProcess(entity.getRId(), GaugeType.QUESTIONNAIRE, entity.getAnswerRecords());
    }

    @Transactional
    public void submitQuestionnaire(ScaleSubmitDto entity) {
        // 1.查询分配记录
        TblQnrAllotRecord record = qnrAllotRecordMapper.selectRecordWithRid(entity.getAllotId());
        Validate.isFalse(null == record, "分发记录不存在");
        resultMapper.selectById(record.getRId());
        resultMapper.update(null,
                new LambdaUpdateWrapper<TblQnrResult>()
                        .set(TblQnrResult::getStatus, 1)
                        .set(TblQnrResult::getSubmissionTime, LocalDateTime.now())
                        .set(TblQnrResult::getAnswerJson, entity.getAnswerJson())
                        .set(TblQnrResult::getCostTime, entity.getCostTime())
                        .set(TblQnrResult::getAnonymous, record.getAnonymous() && entity.isAnonymous())
                        .eq(TblQnrResult::getId, record.getRId()));
        // step 原始答卷
        gaugeAnswerService.submit(record.getRId(), GaugeType.QUESTIONNAIRE, entity.getAnswerRecords());
    }
}
